<?php defined('SYSPATH') or die('No direct script access.');

/**
 *批量sku库存查询的控制器

 */
class Controller_Report_Skus extends Controller_Admin
{
    /**
     *批量sku库存查询权限

     */
    public function before()
    {
        try{
            ACL::Required('skus');
        }catch(HTTP_Exception_403 $e){
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(TRUE));
        }
        parent::before();
    }

    /**
     *查询的默认首界面

     */
    public function action_index()
    {

        $this->title = __('产品数据报表');

        $view = View::factory('report/skus');

        $this->response->body($view);
    }

    /**
     * 下载模板
     */
    public function action_down_template()
    {
        $this->title = '下载模版';
        require_once(Kohana::find_file('vendor','PHPExcel/PHPExcel/IOFactory'));
        $this->objReader = PHPExcel_IOFactory::createReader('Excel5');
        $objPHPExcel     = new PHPExcel();
        $objPHPExcel->getProperties()
            ->setCreator("newerp")
            ->setLastModifiedBy("newerp")
            ->setTitle("Office 2003 XLSX Test Document")
            ->setSubject("Office 2003 XLSX Test Document")
            ->setDescription("Test document for Office 2003 XLSX, generated using PHP classes.")
            ->setKeywords("office 2003 openxml php")
            ->setCategory("Test result file");
        $objActSheet = $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet->setCellValue('A1','SKU');
        $objPHPExcel->getActiveSheet()
            ->setTitle('load');
        $objPHPExcel->setActiveSheetIndex(0);
        $day = date("m-d");
        ob_end_clean();
        header("Content-Type: application/vnd.ms-excel; charset=utf-8");
        header('Content-Disposition: attachment;filename="'.$day.'产品数据.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 批量导入sku，下载数据
     */
    public function action_download()
    {
        set_time_limit(0);
        ini_set('memory_limit','500M');
        require_once(Kohana::find_file('vendor','PHPExcel/PHPExcel/IOFactory'));
        $xls         = $_FILES['xls']['tmp_name'];
        $objPHPExcel = PHPExcel_IOFactory::load($xls);
        $data        = $objPHPExcel->getActiveSheet()
            ->toArray(NULL,TRUE,TRUE,TRUE);
        $num         = count($data);
        $error_arr   = array(); //存储不合格的行
        $begin_time  = time();
        $skus_execl  = $skus_arr = $error_num = $sku_error_arr = array();

        $sku_str = '';
        for($i = 2;$i<=$num;$i++){
            $skus_execl[$i] = strtoupper(trim($data[$i]['A']));
            $sku_str .= $sku_str==''?"'".trim($data[$i]['A'])."'":",'".trim($data[$i]['A'])."'";
        }
        $storage_all = $skusname = array();
        if($sku_str!=''){
            //START     ----------------------------------CWY更新代码-------------------------------------
            $skus_arr = Skusystemapi::getSkuIn($sku_str);
            if(!empty($skus_arr)){
                foreach($skus_arr as $__sku){
//                    $price                      = Skusystemapi::getSkuPrice($__sku['sku']);
                    $place                      = Skusystemapi::getSkuPlace($__sku['sku']);
                    $cnname                     = Skusystemapi::getSkuCnname($__sku['sku']);
                    $storage_all[$__sku['sku']] = isset($place[0]['place'])?$place[0]['place']:'';
                    $skusname[$__sku['sku']]    = $cnname[0]['name'];
                }
                //END     ----------------------------------CWY更新代码-------------------------------------
                $skus_arr      = Arr::pluck($skus_arr,'sku');
                $skus_arr      = array_intersect($skus_execl,$skus_arr);
                $sku_error_arr = array_diff($skus_execl,$skus_arr);
                if($sku_error_arr){
                    $error_num = array_keys($sku_error_arr);
                }
            }
        }
        $actual_num_all = $op_print_num_all = $skuinfo = array();
        if($sku_str){
            //实际库存信息
            $actual_num_all = Warningtmp::get_inventory($skus_arr);
            //订单占用库存信息
            $op_print_num_all = Warningtmp::get_print_num($skus_arr);
            //			}
            //sku状态
            $skuinfo = Basic::get_sku_status($skus_arr);
        }

        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()
            ->setCreator("YKS")
            ->setLastModifiedBy("YKS")
            ->setTitle("Office 2003 XLSX Test Document")
            ->setSubject("Office 2003 XLSX Test Document")
            ->setDescription("Test document for Office 2003 XLSX, generated using PHP classes.")
            ->setKeywords("office 2003 openxml php")
            ->setCategory("Test result file");
        $objActSheet = $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet->setCellValue('A1','SKU');
        $objActSheet->setCellValue('B1','中文名称');
        $objActSheet->setCellValue('C1','储位');
        $objActSheet->setCellValue('D1','实际库存');
        $objActSheet->setCellValue('E1','库存可用');
        $objActSheet->setCellValue('F1','在售状态');

        $counter = 0;
        foreach($skus_arr as $num => $sku){
            $actual_temp       = isset($actual_num_all[$sku])?$actual_num_all[$sku]:0;
            $op_print_num_temp = isset($op_print_num_all[$sku])?$op_print_num_all[$sku]:0;
            $keyong            = $actual_temp-$op_print_num_temp;
            $skusname[$sku]=isset($skusname[$sku])?$skusname[$sku]:'-';
            $storage_all[$sku]=isset($storage_all[$sku])?$storage_all[$sku]:'-';
            $skuinfo[$sku]['status_string']=isset($skuinfo[$sku]['status_string'])?$skuinfo[$sku]['status_string']:'-';

            $objActSheet->setCellValue('A'.(($counter+2)),$sku);
            $objActSheet->setCellValue('B'.(($counter+2)),$skusname[$sku]);
            $objActSheet->setCellValue('C'.($counter+2),$storage_all[$sku]);
            $objActSheet->setCellValue('D'.($counter+2),$actual_temp);
            $objActSheet->setCellValue('E'.($counter+2),$keyong);
            $objActSheet->setCellValue('F'.($counter+2),$skuinfo[$sku]['status_string']);
            $counter++;
        }
        if($sku_error_arr){
            $error_num = 0;
            $numbers   = count($skus_arr)+2;
            $objActSheet->setCellValue('A'.$numbers,'以下SKU找不到或者找不到数据');
            $error_num++;
            foreach($sku_error_arr as $_sku){
                $objActSheet->setCellValue('A'.($numbers+$error_num),$_sku);
                $error_num++;
            }
        }
        $objPHPExcel->getActiveSheet()
            ->setTitle('产品数据报表');
        $objPHPExcel->setActiveSheetIndex(0);
        $day      = date("m-d");
        $filename = $day.'产品数据报表'.'.xls';
        ob_end_clean();
        header("Content-Type: application/vnd.ms-excel; charset=utf-8");
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        $objWriter->save('php://output');
        exit;
    }
}
